#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import cv2 
import json
import os

L = []
for root,dirs,files in os.walk('./0json/'):
    for file in files:
        if os.path.splitext(file)[1]=='.json':
            L.append(root+file)
category_types = ['background','wire_copper','pad_copper','chip','capacitor','resistor','diode','pin_straight','pin_bent','pin_type_01','solder_joint']
#                   [浅黄,      ，   淡紫色 ，   灰色  ，   橘色    ，  绿  ，   浅蓝   ，   蓝色 ，   黄色，  ,    白色 ，     红色]
# In[4]:

#color = np.array([[143,246,255],[255,187,255],[181,181,181],[0,165,255],[0,255,0],[255,191,0],[255,0,0],[0,255,255],[255,255,255],[0,0,255]])

color = np.array([[0,0,0],[0,0,255],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[255,0,0],[0,255,0],[255,0,0],[0,0,255]])

for pic_num in range (len(L)):
#for pic_num in range (2):
    with open(L[pic_num],"r") as f:
        result = json.load(f)
    h = result["imageHeight"]
    w = result["imageWidth"]
    mask = np.zeros([h,w,1],np.uint8)
    shapes = result["shapes"]
    shapes_sort = sorted(shapes, key=lambda shape: category_types.index(shape['label']), reverse=True)

    
    for shape in shapes_sort:
        category = shape["label"]
        points = shape["points"]
        points_array = np.array(points,dtype=np.int32)


        #mask = cv2.fillPoly(mask,[points_array],category_types.index(category)*25+25)
        if category == "solder_joint" :  #or category == "pad_copper":
            mask = cv2.fillPoly(mask,[points_array],50)
        elif category == "pin_type_01" or category == "pin_bent" or category == "pin_straight":
            mask = cv2.fillPoly(mask,[points_array],25)
        elif category == "resistor" or category == "diode" or category == "capacitor" or category == "chip":
            mask = cv2.fillPoly(mask,[points_array],75)
        elif category == "background":
            mask = cv2.fillPoly(mask,[points_array],0)
    
    cv2.imwrite("1label_4/"+result['imagePath'].split('.')[0]+'.png',mask)
    pic = cv2.imread('1image/' + result['imagePath'])
    #cv2.imwrite("1image_temp/"+result['imagePath'].split('.')[0]+'.jpg',pic)
    temp = np.zeros([h,w,3],np.uint8)
    #for i in range(10):
    #    temp += (mask==(25+25*i))*color[i].astype('uint8')
    temp += (mask==50)* color[9].astype('uint8')
    temp += (mask==25)* color[8].astype('uint8')
    temp += (mask==75)* color[7].astype('uint8')

    showpic=cv2.addWeighted(pic,0.4,temp,0.6,0)
    cv2.imwrite("1show_4/"+result['imagePath'].split('.')[0]+'.jpg',showpic)

# In[6]:


#cv2.imwrite("mask/"+result['imagePath'],mask)

# In[1]:
#showpic = ((pic)*((255-mask)/255*0.25+mask/255)).astype("uint8")
#colors = [[np.random.randint(0,255)for _ in range(3)]for _ in range(10)]
#showpic = (pic+mask/255*color).astype("uint8")


#cv2.imshow("showpic",showpic)
#cv2.waitKey(0)





